<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/30
 * Time: 16:20
 */
namespace app\api\common;
use Des3\DES3;
use think\Controller;
use think\Db;
use think\Exception;

class Login extends Controller
{
    protected static $err_code = 0;

    /**
     *
     * @apiGroup Login
     * @apiVersion 1.0.1
     * @apiDescription 登录接口
     * @api {post} /login.login 登录接口
     * @apiName Login_login
     * @apiParam {String} phone 用户手机号码 (DES3)加密
     * @apiParam {String} password 用户密码 (DES3)加密
     * @apiParam {String} device_id 手机设备号
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 数据对象
     * @apiSuccess {int} data.token token
     * @apiSuccess {String} data.base.member_id

     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *           ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public static function login($param){
        try{
            if (!isset($param['phone']) || empty($param['phone'])){
                self::$err_code = 400001;
                throw new Exception('请输入手机号码');
            }
            if (!isset($param['password']) || empty($param['password'])){
                self::$err_code = 400002;
                throw new Exception('请输入密码');
            }
            $des = new DES3();
            $phone = $des->decrypt($param['phone']);
            $validate_common = validate('api/Common');
            if (!$validate_common->scene('check_phone')->check(['phone' => $phone])){
                self::$err_code = $validate_common->getError();
                throw new Exception(config('error_code.'.self::$err_code));
            }
            $password = $des->decrypt($param['password']);
            // 验证密码
            $validate_login = validate('api/Login');
            if (!$validate_login->scene('password_login')->check(['password' => $password])) {
                self::$err_code = $validate_login->getError();
                throw new Exception(config('error_code.'.self::$err_code));
            }
            $password = md5(md5($password) . md5($phone));
            $member   = db('member')->where('phone', $phone)->where('password', $password)->find();
            if (!$member) {
                self::$err_code = 400008;
                throw new Exception(config('error_code.'.self::$err_code));
            }
            //判断用户是否被禁用
            if ($member['status'] != 1) {
                self::$err_code = 400009;
                throw new Exception(config('error_code.'.self::$err_code));
            }
            $baseInfo = [
                'member_id'        => $member['id'],
                'phone'            => $member['phone'],
                'password'         => $member['password'],
                'wx_openid'           => $member['wx_openid'],
                'unionid'          => $member['unionid'],
                'sex'          => $member['sex'],
                'qq'          => $member['qq'],
                'wechat'          => $member['wechat'],
                'birthday'          => $member['birthday'],
                'signature'          => $member['signature'],
                'headimgurl'          => $member['headimgurl'],
                'nickname'          => $member['nickname'],
                'user_device_id'          => $param['device_id'],
            ];
            $update_data['last_login_time'] = time();
            $update_data['last_login_ip'] = getIPaddress();
            $update_data['user_device_id'] = $param['device_id'];
            db('member')->where('id', $member['id'])->update($update_data);
            $data['base'] = $baseInfo;
            $token = get_uuid();
            $data['token'] = ['expire' => time()+config('time_expire'),'token' => $token];
            cache($token,$baseInfo);
            $return = $des->encrypt(json_encode($data));
            return api_return(200, $return);
        }catch (Exception $e){
            return ['code'=>self::$err_code,'msg'=>$e->getMessage()];
        }
    }


    /**
     *
     * @apiGroup Login
     * @apiVersion 1.0.1
     * @apiDescription 验证码登录接口
     * @api {post} /login.code_login 验证码登录接口
     * @apiName Login_code_login
     * @apiParam {String} phone 用户手机号码 (DES3)加密
     * @apiParam {int} code 验证码
     * @apiParam {String} device_id 手机设备号
     * @apiParam {String} login_source 登录来源 安卓：android，苹果：ios
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 数据对象
     * @apiSuccess {String} data.token.token 新的token
     * @apiSuccess {int} data.token.expire 过期时间
     * @apiSuccess {int} data.base.member_id 用户id
     * @apiSuccess {String} data.base.phone 用户手机号
     * @apiSuccess {String} data.base.openid 淘宝openid
     * @apiSuccess {int} data.base.sex 用户性别
     * @apiSuccess {String} data.base.headimgurl 用户头像
     * @apiSuccess {String} data.base.nickname 用户昵称
     * @apiSuccess {int} data.base.tb_band 是否已绑定淘宝
     * @apiSuccess {int} data.base.status 用户状态
     * @apiSuccess {String} data.base.login_device_id 设备号

     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *           ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public static function code_login($param){
        try{
            if (!isset($param['phone']) || empty($param['phone'])){
                self::$err_code = 400001;
                throw new Exception('请输入手机号码');
            }
            if (!isset($param['code']) || empty($param['code'])){
                self::$err_code = 400001;
                throw new Exception('请输入验证码');
            }
            $des = new DES3();
            $phone = $des->decrypt($param['phone']);
            $validate_common = validate('api/Common');
            if (!$validate_common->scene('check_phone')->check(['phone' => $phone])){
                self::$err_code = $validate_common->getError();
                throw new Exception(config('error_code.'.self::$err_code));
            }

            // 验证短信验证码是否有效
            $check_code = check_send_code($param['code'], $param['phone'], 3);
            if ($check_code['code'] != 200)
            {
                self::$err_code = $check_code['code'];
                throw new Exception($check_code['msg']);
            }
            $member   = db('member')->where('phone', $phone)->find(); //查找是否已经注册

            if ($member){
                //判断用户是否被禁用
                if ($member['status'] != 1) {
                    self::$err_code = 400009;
                    throw new Exception(config('error_code.'.self::$err_code));
                }
                //返回的用户信息
                $baseInfo = [
                    'member_id'        => $member['id'], //用户id
                    'phone'            => $member['phone'], //手机号
                    'openid'           => $member['openid'], //淘宝openid
                    'sex'          => $member['sex'], //性别
                    'headimgurl'          => get_img_url($member['headimgurl'],'headimgurl'),//头像
                    'nickname'          => $member['nickname'],//昵称
                    'status'          => $member['status'],//状态
                    'tb_band'          => $member['tb_band']//是否绑定
                ];
            }else{
                // 验证码登录 用户不存在时 自动注册
                $register_data               = [
                    'phone'   => $phone,//手机号
                    'reg_ip'   => getIPaddress(),//注册ip
                    'reg_time'   => time(),//注册时间
                    'last_login_ip'       => getIPaddress(),//登录ip
                    'last_login_time'       => time(),//最后登录时间
                    'reg_device_id'    => $param['device_id'],//用户设备id
                    'login_device_id'    => $param['device_id'],//用户设备id
                    'reg_source'    => $param['login_source'],//注册来源（安卓：android ,苹果：ios）
                    'login_source'    => $param['login_source'],//登录来源（安卓：android ,苹果：ios）
                    'tb_band'   => 0, //淘宝绑定状态 0：未绑定；  1：已绑定；  2：已取消
                ];
                $rs = Db::table('yf_member')->insertGetId($register_data);//插入数据库
                $baseInfo = [
                    'member_id'        => $rs, //用户id
                    'phone'            => $phone, //手机号
                    'openid'           =>'', //淘宝openid
                    'sex'                => 0, //性别
                    'headimgurl'          => get_img_url('','headimgurl'), //头像
                    'nickname'          => '', //用户名
                    'tb_band'          => 0, //绑定状态
                    'status'          => 1, //会员状态
                ];
            }
            $update_data['last_login_time'] = time();
            $update_data['last_login_ip'] = getIPaddress();
            $update_data['login_device_id'] = $param['device_id'];
            db('member')->where('id', $member['id'])->update($update_data);
            $data['base'] = $baseInfo;
            $token = get_uuid();
            $data['token'] = ['expire' => time()+config('time_expire'),'token' => $token];
            cache($token,$baseInfo);
            $return = $des->encrypt(json_encode($data));
            return ['code'=>200,'msg'=>'success','data'=>$return];
        }catch (Exception $e){
            return ['code'=>self::$err_code,'msg'=>$e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Login
     * @apiVersion 1.0.1
     * @apiDescription 淘宝授权登录接口
     * @api {post} /login.tb_login 淘宝授权登录接口
     * @apiName Login_tb_login
     * @apiParam {String} openid 淘宝openid(DES3)加密
     * @apiParam {String} headimgurl 用户头像
     * @apiParam {String} nickname 昵称
     * @apiParam {String} device_id 手机设备号
     * @apiParam {String} login_scene 登录场景（安卓：android ,苹果：ios）
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 数据对象
     * @apiSuccess {String} data.token.token 新的token
     * @apiSuccess {int} data.token.expire 过期时间
     * @apiSuccess {String} data.base.member_id 用户id
     * @apiSuccess {String} data.base.phone 用户手机号
     * @apiSuccess {String} data.base.openid 淘宝openid
     * @apiSuccess {int} data.base.sex 用户性别
     * @apiSuccess {String} data.base.headimgurl 用户头像
     * @apiSuccess {String} data.base.nickname 用户昵称
     * @apiSuccess {int} data.base.tb_band 是否已绑定淘宝
     * @apiSuccess {int} data.base.status 用户状态
     * @apiSuccess {String} data.base.login_device_id 设备号
     *
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *           ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public static function tb_login($param)
    {
        if (!isset($param['openid']) || empty($param['openid'])) {
            return json(['code'=>400001,'data'=>[],'msg'=>'参数错误']);
        }
        //启动事物
        Db::startTrans();
        try{
            $des = new DES3();
            $openid = $des->decrypt($param['openid']);
            if (empty($openid)) {
                self::$err_code = 400001;
                throw new Exception('openid参数错误');
            }
            $member = Db::table('yf_member')->where('openid', $param['openid'])->find();//查询用户信息
            if (!$member) {
                // 验证码登录 用户不存在时 自动注册
                $register_data               = [
                    'reg_ip'   => getIPaddress(),//注册ip
                    'reg_time'   => time(),//注册时间
                    'last_login_ip'       => getIPaddress(),//登录ip
                    'last_login_time'       => time(),//最后登录时间
                    'openid'    => $openid,//淘宝openid
                    'reg_device_id'    => $param['device_id'],//用户设备id
                    'login_device_id'    => $param['device_id'],//用户设备id
                    'reg_source'    => $param['login_scene'],//注册来源（安卓：android ,苹果：ios）
                    'login_source'    => $param['login_scene'],//登录来源（安卓：android ,苹果：ios）
                    'headimgurl' => $param['headimgurl'],//用户头像
                    'nickname'   => $param['nickname'],//用户昵称
                    'tb_band'   => 0 //淘宝绑定状态 0：未绑定；  1：已绑定；  2：已取消
                ];
                $rs = Db::table('yf_member')->insertGetId($register_data);//插入数据库
                $baseInfo = [
                    'member_id'        => $rs, //用户id
                    'phone'            => '', //手机号
                    'openid'           => $register_data['openid'], //淘宝openid
                    'sex'                => 0, //性别
                    'headimgurl'          => $member['headimgurl'], //头像
                    'nickname'          => $member['nickname'], //用户名
                    'tb_band'          => 0, //绑定状态
                    'status'          => 1, //会员状态
                    'login_device_id'          => $param['device_id'], //用户手机设备号
                ];
            } else {
                //添加头像跟昵称
                if (!empty($param['headimgurl']) || !empty($param['nickname'])) {
                    $info_data['headimgurl']= trim($param['headimgurl']);
                    $info_data['nickname']= trim($param['nickname']);
                }
                $info_data['last_login_time']= time();
                $info_data['last_login_ip']= getIPaddress();
                $info_data['login_device_id']= $param['device_id'];
                $info_data['login_source']= $param['login_scene'];
                Db::table('yf_member')->where(['id' => $member['id']])->update($info_data);
                $baseInfo = [
                    'member_id'        => $member['id'], //用户id
                    'phone'            => $member['phone'], //手机号
                    'openid'           => $member['openid'], //淘宝openid
                    'sex'                => $member['sex'], //性别
                    'headimgurl'          => $param['headimgurl'], //头像
                    'nickname'          => $param['nickname'], //用户名
                    'tb_band'          => $param['tb_band'], //用户名
                    'login_device_id'          => $param['device_id'], //用户手机设备号
                    'status'          => $member['status'], //会员状态
                ];
            }
            $datas['base'] = $baseInfo;
            $token = self::get_uuid();
            $datas['token'] = ['expire' => time()+config('time_expire'),'token' => $token];
            cache($token,$datas);
            $return = $des->encrypt(json_encode($datas));
            //事物提交
            Db::commit();
            return json(['code'=>200,'data'=>$return,'msg'=>'success']);
        }catch (Exception $e){
            //事物回滚
            Db::rollback();
            return json(['code'=>self::$err_code,'data'=>[],'msg'=>$e->getMessage()]);
        }
    }

    /**
     *
     * @apiGroup Login
     * @apiVersion 1.0.1
     * @apiDescription 注册接口
     * @api {post} /login.register 注册接口
     * @apiName Login_register
     * @apiParam {String} phone 用户手机号码 (DES3)加密
     * @apiParam {String} password 用户密码 (DES3)加密
     * @apiParam {int} code 短信验证码
     * @apiParam {String} reg_source 注册来源（安卓：android ,苹果：ios）
     * @apiParam {String} user_device_id 设备号
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 数据对象
     * @apiSuccess {int} data.member_id 用户id
     * @apiSuccess {String} data.headimgurl 默认头像
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *           ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public static function register($param)
    {
        // 启动事务
        Db::startTrans();
        try
        {
            if (!isset($param['phone']) || empty($param['phone'])){
                self::$err_code = 400001;
                throw new Exception('请输入手机号码');
            }
            if (!isset($param['password']) || empty($param['password'])){
                self::$err_code = 400002;
                throw new Exception('请输入密码');
            }
            // 解密数据
            $des = new DES3();
            $param['phone'] = $des->decrypt($param['phone']);
            $param['password'] = $des->decrypt($param['password']);
            // 验证注册参数 是否提交完成
            $validate_register = validate('api/Login');
            if (!$validate_register->scene('register')->check($param))
            {
                self::$err_code = $validate_register->getError();
                throw new Exception(config('error_code.'.self::$err_code));
            }
            // 解密数据
            $register_data['phone'] = $param['phone'];
            $register_data['password'] = $param['password'];
            // 验证数据有效性
            if (!$validate_register->scene('register_add')->check($register_data))
            {
                self::$err_code = $validate_register->getError();
                throw new Exception(config('error_code.'.self::$err_code));
            }
            // 组装注册用户数据
            $data['phone'] = $register_data['phone'];
            $data['password'] = md5(md5($register_data['password']) . md5($register_data['phone']));
            // 验证短信验证码是否有效
            $check_code = check_send_code($param['code'], $register_data['phone'], 1);
            if ($check_code['code'] != 200)
            {
                self::$err_code = $check_code['code'];
                throw new Exception($check_code['msg']);
            }
            $data['reg_time'] = time(); // 注册时间
            $data['reg_ip'] = getIPaddress(); // 注册ip
            $data['last_login_ip'] = getIPaddress(); // 注册ip
            $data['last_login_time'] = time(); // 初始化登录时间
            $data['reg_source'] = empty($param['reg_source']) ? '' : $param['reg_source']; // 注册来源 2017-08-15
            $rs = Db::table('yf_member')->insertGetId($data);
            $baseInfo = [
                'member_id'        => $rs,
                'phone'            => $data['phone'],
                'wx_openid'           => '',
                'wx_band'           => 0,
                'wb_openid'           => '',
                'wb_band'           => 0,
                'unionid'          => '',
                'sex'          => '',
                'qq'          => '',
                'wechat'          => '',
                'birthday'          => '',
                'signature'          => '',
                'headimgurl'          => '',
                'nickname'          => '',
                'user_device_id'          =>  $param['user_device_id'],  //设备号
            ];
            $datas['base'] = $baseInfo;
            $token = get_uuid();
            $datas['token'] = ['expire' => time()+config('time_expire'),'token' => $token];
            cache($token,$datas);
            Db::commit();
            $return = $des->encrypt(json_encode($datas));
            return api_return(200, $return);
        }
        catch (Exception $e)
        {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code,'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Login
     * @apiVersion 2.0.2
     * @apiDescription 忘记密码
     * @api {post} /login.retrieve_password 找回密码
     * @apiName Login_retrieve_password
     * @apiParam {String} phone 用户手机号码 (DES3)加密
     * @apiParam {String} password 用户新密码 (DES3)加密
     * @apiParam {int} code 短信验证码

     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */

    public static function retrieve_password($param)
    {
        // 启动事务
        Db::startTrans();
        try
        {
            // 解密数据
            $des = new DES3();
            $param['phone'] = $des->decrypt($param['phone']);
            $param['password'] = $des->decrypt($param['password']);

            // 验证找回密码参数 是否提交完成 -- 与注册接口一直
            $validate_register = validate('api/Login');
            if (!$validate_register->scene('register')->check($param))
            {
                self::$err_code = $validate_register->getError();
                throw new Exception(config('error_code.'.self::$err_code));
            }

            // 验证数据有效性
            if (!$validate_register->scene('retrieve_password')->check($param))
            {
                self::$err_code = $validate_register->getError();
                throw new Exception(config('error_code.'.self::$err_code));
            }

            // 检查帐号是否存在
            $member = Db::table('yf_member')->where('phone', $param['phone'])->find();
            if (!$member)
            {
                self::$err_code = 400022;
                throw new Exception(config('error_code.'.self::$err_code));
            }

            // 验证短信验证码是否有效
            $check_code = check_send_code($param['code'], $param['phone'], 2);
            if ($check_code['code'] != 200)
            {
                self::$err_code = $check_code['code'];
                throw new Exception($check_code['msg']);
            }

            // 加密用户密码
            $data['password'] = md5(md5($param['password']) . md5($param['phone']));
            // 写入数据库
            Db::table('yf_member')->where('phone', $param['phone'])->update($data);
            Db::commit();
            return ['code' => 200, 'msg' => 'SUCCESS'];
        }
        catch ( Exception $e)
        {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' =>  $e->getMessage()];
        }
    }


    /**
     *
     * @apiGroup Login
     * @apiVersion 2.0.2
     * @apiDescription 检查手机号是否绑定淘宝
     * @api {post} /login.check_phone_is_band 检查手机号是否绑定淘宝了
     * @apiName Login_check_phone_is_band
     * @apiParam {String} phone 绑定的手机号（des3加密）
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public static function check_phone_is_band($param)
    {
        if (!isset($param['phone']))
        {
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        try
        {
            $des = new DES3();
            $phone = $des->decrypt($param['phone']);
            $member = Db::table('yf_member')->where('phone',$phone)->find();
            if ($member['openid'])
            {
                return json(['code'=>400181,'msg'=>'该手机号码已绑定淘宝','data'=>[]]);
            }else{
                return json(['code'=>200,'msg'=>'success','data'=>[]]);
            }
        }
        catch (\Exception $e)
        {
            return ['code' => self::$err_code,'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Login
     * @apiVersion 2.0.2
     * @apiDescription 绑定淘宝号
     * @api {post} /login.tb_band 绑定淘宝号
     * @apiName Login_tb_band
     * @apiParam {String} phone 手机号（des3加密）
     * @apiParam {String} openid 淘宝openid(DES3)加密
     * @apiParam {String} headimgurl 用户头像
     * @apiParam {String} nickname 昵称
     * @apiParam {String} token
     * @apiParam {String} sign
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 数据对象
     * @apiSuccess {String} data.token.token 新的token
     * @apiSuccess {int} data.token.expire 过期时间
     * @apiSuccess {int} data.base.member_id 用户id
     * @apiSuccess {String} data.base.phone 用户手机号
     * @apiSuccess {String} data.base.openid 淘宝openid
     * @apiSuccess {int} data.base.sex 用户性别
     * @apiSuccess {String} data.base.headimgurl 用户头像
     * @apiSuccess {String} data.base.nickname 用户昵称
     * @apiSuccess {int} data.base.tb_band 是否已绑定淘宝
     * @apiSuccess {int} data.base.status 用户状态
     * @apiSuccess {String} data.base.login_device_id 设备号
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public function tb_band($param){
        Db::startTrans();
        try{
            if (!isset($param['phone']) || empty($param['phone'])){
                self::$err_code = 400001;
                throw new Exception('请输入手机号码');
            }
            if (!isset($param['openid']) || empty($param['openid'])){
                self::$err_code = 400001;
                throw new Exception('请输入openid');
            }
            $des = new DES3();
            $phone = $des->decrypt($param['phone']);
            $openid = $des->decrypt($param['openid']);
            $member_info = Db::table('yf_member')->field('id,tb_band,nickname,headimgurl,sex,status,login_device_id')->where('phone',$phone)->find();
            if ($member_info['tb_band'] == 1 ){
                self::$err_code = 400001;
                throw new Exception('该账户已绑定其他淘宝号');
            }
            $data['headimgurl'] = $param['headimgurl'];
            $data['nickname'] = $param['nickname'];
            $data['openid'] = $openid;
            $data['tb_band'] = 1;
            $flag = Db::table('yf_member')->where('phone',$phone)->update($data);
            if ($flag){
                $baseInfo = [
                    'member_id'        => $member_info['id'], //用户id
                    'phone'            => $phone, //手机号
                    'openid'           => $openid, //淘宝openid
                    'sex'                => $member_info['sex'], //性别
                    'headimgurl'          =>  $param['headimgurl'], //头像
                    'nickname'          => $param['nickname'], //用户名
                    'tb_band'          => 1, //绑定状态
                    'status'          => $member_info['status'], //会员状态
                    'login_device_id'          => $member_info['login_device_id'], //用户手机设备号
                ];
                $datas['base'] = $baseInfo;
                $token = self::get_uuid();
                $datas['token'] = ['expire' => time()+config('time_expire'),'token' => $token];
                cache($token,$datas);
                $return = $des->encrypt(json_encode($datas));
                Db::commit();
                return json(['code'=>200,'msg'=>'success','data'=>$return]);
            }else{

                throw new Exception('信息更新失败');
            }

        }catch (Exception $e){
            Db::rollback();
            return json(['code'=>self::$err_code,'msg'=>$e->getMessage(),'data'=>[]]);
        }
    }


    /**
     *
     * @apiGroup Login
     * @apiVersion 2.0.2
     * @apiDescription 绑定手机号
     * @api {post} /login.phone_band 绑定手机号
     * @apiName Login_phone_band
     * @apiParam {String} phone 手机号（des3加密）
     * @apiParam {String} openid 淘宝openid(DES3)加密
     * @apiParam {String} token
     * @apiParam {String} sign
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data 数据对象
     * @apiSuccess {String} data.token.token 新的token
     * @apiSuccess {int} data.token.expire 过期时间
     * @apiSuccess {int} data.base.member_id 用户id
     * @apiSuccess {String} data.base.phone 用户手机号
     * @apiSuccess {String} data.base.openid 淘宝openid
     * @apiSuccess {int} data.base.sex 用户性别
     * @apiSuccess {String} data.base.headimgurl 用户头像
     * @apiSuccess {String} data.base.nickname 用户昵称
     * @apiSuccess {int} data.base.tb_band 是否已绑定淘宝
     * @apiSuccess {int} data.base.status 用户状态
     * @apiSuccess {String} data.base.login_device_id 设备号
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public function phone_band($param){
        Db::startTrans();
        try{
            if (!isset($param['phone']) || empty($param['phone'])){
                self::$err_code = 400001;
                throw new Exception('请输入手机号码');
            }
            if (!isset($param['openid']) || empty($param['openid'])){
                self::$err_code = 400001;
                throw new Exception('请输入openid');
            }
            $des = new DES3();
            $phone = $des->decrypt($param['phone']);
            $openid = $des->decrypt($param['openid']);
            $member_info = Db::table('yf_member')->field('id,tb_band,nickname,headimgurl,sex,status,login_device_id')->where('openid',$openid)->find();
            if (!empty($member_info['phone'])){
                self::$err_code = 400001;
                throw new Exception('该账户已绑定其他手机号');
            }
            $flag = Db::table('yf_member')->where('openid',$openid)->update(['phone'=>$phone,'tb_band'=>1]);
            if ($flag){
                $baseInfo = [
                    'member_id'        => $member_info['id'], //用户id
                    'phone'            => $phone, //手机号
                    'openid'           => $openid, //淘宝openid
                    'sex'                => $member_info['sex'], //性别
                    'headimgurl'          =>  $member_info['headimgurl'], //头像
                    'nickname'          => $member_info['nickname'], //用户名
                    'tb_band'          => 1, //绑定状态
                    'status'          => $member_info['status'], //会员状态
                    'login_device_id'          => $member_info['login_device_id'], //用户手机设备号
                ];
                $datas['base'] = $baseInfo;
                $token = self::get_uuid();
                $datas['token'] = ['expire' => time()+config('time_expire'),'token' => $token];
                cache($token,$datas);
                $return = $des->encrypt(json_encode($datas));
                Db::commit();
                return json(['code'=>200,'msg'=>'success','data'=>$return]);
            }else{

                throw new Exception('信息更新失败');
            }

        }catch (Exception $e){
            Db::rollback();
            return json(['code'=>self::$err_code,'msg'=>$e->getMessage(),'data'=>[]]);
        }
    }






    /**
     * @desc 获取唯一码
     */
    public static function get_uuid(){
        static $uuid = '';
        $uid = uniqid("", true);
        $data = time().$_SERVER['REQUEST_TIME'].$_SERVER['REMOTE_ADDR'].rand(1111,9999);
        $uuid = strtoupper(hash('ripemd128',$uid.$uuid.md5($data)));
        return $uuid;
    }

}